package br.com.flexdev.view.service
{
	import com.digows.components.util.Msg;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.Operation;
	import mx.rpc.remoting.mxml.RemoteObject;


	public class RemoteConnection
	{	
		public function RemoteConnection(){}
		
		/**
		* Método que trata quando há algum erro de 
		* Conexão com o GraniteDataServices
		*
		* @param event:FaultEvent
		*/
		public static function onConnectionFault(event:FaultEvent):void 
		{
			Msg.erro( event.fault.faultString );
		}
		
		/**
		* Conecta com um servico no GraniteDataServices
		*
		* @param servicoPHP Nome do Servico no GraniteDataServices
		* @param Método da Classe
		* @callBack Função de Retorno do Método Assincrono
		* @parameters Parâmetros para o Método
		*/
		public static function call(servico:String, metodo:String, callBack:Function, ...parameters):void 
		{
			var connection:RemoteObject = new RemoteObject("graniteamf");
			connection.source = servico;
			connection.showBusyCursor = true;
			connection.addEventListener(FaultEvent.FAULT, RemoteConnection.onConnectionFault);
			
			var op:Operation = connection.getOperation(metodo) as Operation;
			op.addEventListener(ResultEvent.RESULT, callBack);
			
			switch (parameters.length)
			{
				case 0:
					op.send();
				break;
				case 1:
					op.send(parameters[0]);
				break;
				case 2:
					op.send(parameters[0], parameters[1]);
				break;
				case 3:
					op.send(parameters[0], parameters[1], parameters[2]);
				break;
				case 4:
					op.send(parameters[0], parameters[1], parameters[2], parameters[3]);
				break;
				case 5:
					op.send(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]);
				break;
				default:
					op.send(parameters);
				break;
			}
		}
	}
}

